<template>
  <el-container>
    <el-header width="200px">
      <Header/>
    </el-header>
    <el-main>
      <div>
        <!-- 查询框开始 -->
        <div style="padding: 10px 0;">
          <el-input style="width: 200px" placeholder="请输入图书名称" v-model="searchObj.name"
                    prefix-icon="el-icon-search" clearable></el-input>
          <el-input style="width: 200px; margin-left: 10px " placeholder="请输入作者名称" v-model="searchObj.author"
                    prefix-icon="el-icon-user" clearable></el-input>
          <el-input style="width: 200px; margin-left: 10px" placeholder="请输入出版社名称" v-model="searchObj.pubCompany"
                    prefix-icon="el-icon-office-building" clearable></el-input>
          <el-input style="width: 200px; margin-left: 10px" placeholder="最低价格" v-model="searchObj.minPrice"
                    clearable></el-input>
          <el-input style="width: 200px; margin-left: 10px" placeholder="最高价格" v-model="searchObj.maxPrice"
                    prefix-icon="el-icon-money"></el-input>
          <el-button style="margin-left: 10px" type="primary" icon="el-icon-search" @click="getList()">查询</el-button>
          <el-button type="primary" plain icon="el-icon-refresh-right" @click="resetData()">重置</el-button>
        </div>
        <!-- 查询框结束 -->

        <div style="margin: 10px 0">
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAddBook()">新增</el-button>
          <el-button type="danger" icon="el-icon-remove-outline" @click="batchRemoveBook(row)">批量删除</el-button>
        </div>

        <!-- 表格开始 -->
        <el-table :data="tableData" border stripe
                  :header-cell-class-name="'headerBg'" @selection-change="handleSelectionChange"
                  :cell-style="{textAlign:'center'}" :header-cell-style="{textAlign:'center'}">
          <el-table-column type="selection" width="40" align="center"></el-table-column>
          <el-table-column prop="no" label="编号" width="80"></el-table-column>
          <el-table-column prop="name" label="名称" align="center"></el-table-column>
          <el-table-column prop="price" label="价格" align="center"></el-table-column>
          <el-table-column prop="author" label="作者" align="center"></el-table-column>
          <el-table-column prop="typeNo" label="分类" align="center">
            <template slot-scope="scope">
              {{ getTypeByTypeNo(scope.row.typeNo) }}
            </template>
          </el-table-column>
          <el-table-column prop="pubCompany" label="出版社" align="center"></el-table-column>
          <el-table-column prop="pubTime" label="出版时间" align="center" :formatter="formatDate"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
          <el-table-column prop="updateTime" label="修改时间" align="center"></el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button type="success" icon="el-icon-edit" @click="handleEditBook(scope.row)">编辑
              </el-button>
              <el-button type="danger" icon="el-icon-delete" @click="removeBook(scope.row.no)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 表格结束 -->

        <!-- 分页栏开始 -->
        <div style="padding: 10px">
          <el-pagination
              align="center"
              :current-page="pageObj.pageNum"
              :page-sizes="[10, 15, 20, 25]"
              :page-size="pageObj.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @current-change="getList"
              @size-change="handleSizeChange">
          </el-pagination>
        </div>
        <!-- 分页栏结束 -->

        <!-- 表单开始 -->
        <el-dialog title="图书信息" :visible.sync="dialogFormVisible" width="30%">
          <el-form label-width="80px" v-model="form">
            <el-form-item label="图书名称">
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="分类">
              <el-select v-model="form.typeNo" filterable style="width: 100%">
                <el-option
                    v-for="item in typeOptions"
                    :key="item.no"
                    :label="item.name"
                    :value="item.no">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="价格">
              <el-input v-model="form.price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="出版时间" prop="scheduleDate">
              <el-date-picker
                  placeholder="选择日期"
                  v-model="form.pubTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  format="yyyy 年 MM 月 dd 日"
                  style="width: 100%">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="作者">
              <el-input v-model="form.author" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="出版社">
              <el-input v-model="form.pubCompany" autocomplete="off"></el-input>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveOrUpdate()">保 存</el-button>
          </div>
        </el-dialog>
        <!-- 表单结束 -->
      </div>
    </el-main>
  </el-container>
</template>

<script>
import Header from "@/components/Header";
import book from "@/api/book";
import bookType from "@/api/bookType";

export default {
  name: "Book",
  components:{
    Header
  },
  data() {
    return {
      searchObj: {},  // 条件封装对象
      tableData: [],  // 所有数据
      typeOptions: [], // 图书类型
      total: 0, // 总记录数
      form: {}, // 数据表单
      pageObj: {  // 分页
        pageNum: 1,
        pageSize: 10
      },
      isError: false, // 价格对比
      dialogFormVisible: false, // 展示表单
      multipleSelection: [],  // 多选框
    }
  },
  created() {
    // 打开页面显示数据
    this.getList()
    // 获得图书分类
    this.getBookType()
  },
  methods: {
    // 切换每页数据量
    handleSizeChange(pageSize) {
      this.pageObj.pageSize = pageSize
      this.searchObj.pageSize = this.pageObj.pageSize
      this.getList()
    },
    // 新增图书按钮
    handleAddBook() {
      this.form = {}
      this.dialogFormVisible = true
    },
    // 编辑图书按钮
    handleEditBook(row) {
      this.form = row
      this.dialogFormVisible = true
    },
    // 批量选择
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    // 重置查询表单
    resetData() {
      this.searchObj = {}
      this.getList()
    },
    // 格式化日期
    formatDate(value) {
      if (!value.pubTime) {
        return "";
      }
      const date = new Date(value.pubTime);
      return date.toLocaleDateString();
    },
    // 最小价格不能超过最大价格
    handleMaxPriceBlur() {
      if (this.searchObj.minPrice != null && this.searchObj.minPrice !== "" &&
          this.searchObj.maxPrice != null && this.searchObj.maxPrice !== "" &&
          this.searchObj.minPrice > this.searchObj.maxPrice) {
        this.$message({
          showClose: true,
          message: '最小价格不能超过最大价格',
          type: 'error'
        })
        return false;
      }
      return true;
    },
    // 获得图书信息
    getList(pageNum = 1) {
      if (this.handleMaxPriceBlur()) {
        this.pageObj.pageNum = pageNum
        this.searchObj.pageNum = this.pageObj.pageNum
        book.listBook(this.searchObj).then(res => {
          this.tableData = res.dataList
          this.total = res.total
        }).catch(res => {
          console.error(res)
        })
      }
    },
    getBookType() {
      bookType.listBookType().then(res => {
        this.typeOptions = res.dataList
      }).catch(res => {
        console.error(res)
      })
    },
    getTypeByTypeNo(typeNo) {
      let typeName = '未知分类';
      this.typeOptions.forEach((item) => {
        if (typeNo === item.no) {
          typeName = item.name;
        }
      })
      return typeName;
    },
    // 保存图书
    submitAdd() {
      book.addBook(this.form).then(res => {
        if (res.code === 200) {
          this.$message.success("保存成功")
          // 关闭窗口
          this.dialogFormVisible = false
          // 刷新页面
          this.getList()
        }
      })
    },
    // 修改图书
    submitUpdate() {
      book.updateBook(this.form).then(res => {
        if (res.code === 200) {
          this.$message.success("修改成功")
          // 关闭窗口
          this.dialogFormVisible = false
          // 刷新页面
          this.getList()
        }
      })
    },
    // 判断添加还是修改
    saveOrUpdate() {
      if (!this.form.no) {
        // 没有no，做添加
        this.submitAdd();
      } else {
        // 修改
        this.submitUpdate()
      }
    },
    // 删除图书
    removeBook(no) {
      this.$confirm('此操作将永久删除图书信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const noList = [];
        noList.push(no)
        // 删除图书表
        book.deleteBook(noList).then(res => {
          this.$message.success("删除成功")
          //刷新页面
          this.getList()
        })

      })
    },
    // 删除图书
    batchRemoveBook() {
      this.$confirm('此操作将永久删除多条图书信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const noList = [];
        //遍历数组得到每个no值，设置到noList里面
        for (let i = 0; i < this.multipleSelection.length; i++) {
          const obj = this.multipleSelection[i]
          noList.push(obj.no)
        }
        // 再批量删除图书表
        book.deleteBook(noList).then(res => {
          this.$message.success("删除成功")
          //刷新页面
          this.getList()
        })
      })
    },
  }
}
</script>
